import distance from '@turf/distance/dist/es/index.js'
import {
	point
} from '@turf/helpers/dist/es/index.js'

export function checkDistance(source) {
	return new Promise(function(resolve, reject) {
		uni.getLocation({
			type: 'gcj02',
			geocode: false,
			success: (res) => {
				const sourceLongitude = parseFloat(source[0]);
				const sourceLatitude = parseFloat(source[1]);
				const destLongitude = parseFloat(res.longitude);
				const destLatitude = parseFloat(res.latitude);
				const dist = distance(
					point([sourceLongitude, sourceLatitude]),
					point([destLongitude, destLatitude])) * 1000;
				const config = uni.getStorageSync('config');
				const deviceDistance = parseFloat(config.deviceDistance || 0)
				if (deviceDistance === 0 || dist < deviceDistance) {
					resolve(true)
				} else {
					uni.showToast({
						title: '当前位置不在设备执行范围之内',
						icon: 'none'
					})
					resolve(false)
				}
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

export function getLocation() {
	return new Promise(function(resolve, reject) {
		uni.getLocation({
			type: 'gcj02',
			geocode: false,
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}
